﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinformMqttServer
{
    public partial class Form1 : Form
    {
        public string ServerId { get { return serverIDTextBox.Text; }set { serverIDTextBox.Text = value; } }
        public int Port { get { int.TryParse(portTextBox.Text,out int p); return p; } set { portTextBox.Text = value.ToString(); } }

        public string ServerIp { get { return ipAddrTextBox.Text; } set { ipAddrTextBox.Text = value; } }
        public string BeWatchClientId { get { return beWatchedClientIdTextBox.Text; } set { beWatchedClientIdTextBox.Text = value; } }
        private MqttHostService hostService;
        public Form1()
        {
            InitializeComponent();
            hostService = new MqttHostService(this);
        }
        public void ShowLogMessage(string message)
        {
            logRichTextBox.Invoke(new Action(() => {
                logRichTextBox.AppendText(message + Environment.NewLine);
            }));
        }
        public void Show2ClientList(string clientId)
        {
            richTextBox1.Invoke(new Action(() => {
                richTextBox1.AppendText(clientId + Environment.NewLine);
            }));
        }
        public void DropFromClientList(string clientId)
        {
            richTextBox1.Invoke(new Action(() =>
            {
                var lines = richTextBox1.Lines.ToList();
                lines.RemoveAll(line => line == clientId);
                richTextBox1.Lines = lines.ToArray();
            }));
        }
        public void Show2TopicList(string topic)
        {
            richTextBox2.Invoke(new Action(() => {
                richTextBox2.AppendText(topic + Environment.NewLine);
            }));
        }
        public void DropFromTopicList(string topic)
        {
            richTextBox2.Invoke(new Action(() =>
            {
                var lines = richTextBox2.Lines.ToList();
                lines.RemoveAll(line => line == topic);
                richTextBox2.Lines = lines.ToArray();
            }));
        }
        private void StartServer(object sender, EventArgs e)
        {
            hostService.StartAsync();
        }

        private void CloseServer(object sender, EventArgs e)
        {
            hostService.StopAsync();
        }
    }
}
